package com.example.mallauthserver.controller;

import com.common.utils.R;
import com.example.mallauthserver.controller.vo.UserRegisterVO;
import com.example.mallauthserver.feign.MemberFeginService;
import com.example.mallauthserver.feign.ThirdPartyFeignService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author guanglin.ma
 * @date 2024-01-03 15:27
 */
@Controller
public class RegisterController {

    @Autowired
    MemberFeginService memberFeginService;

    @PostMapping({"/sms/register"})
    public String smsRegister(@Valid UserRegisterVO userRegisterVO, BindingResult bindingResult, Model model) {

        Map<String, String> map = new HashMap<>();
        String key = "mall-sms:" + userRegisterVO.getPhone();
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
            fieldErrorList.forEach(fieldError -> {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            });
            model.addAttribute("error", map);
            return "/register.html";
        } else {
            String redisCode = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isBlank(redisCode)) {
                // 远程调用对应的服务 完成注册功能
                R r = memberFeginService.register(userRegisterVO);
                System.out.println(r.getMsg());
                if (r.getCode() == 0) {
                    // 注册成功
                    return "redirect:http://auth.mg.com/login.html";
                } else {
                    // 注册失败
                    map.put("msg", r.getCode() + ":" + r.get("msg"));
                    model.addAttribute("error", map);
                    return "/register.html";
                }
            } else {
                String code = redisCode.split("-")[0];
                if (StringUtils.isNotBlank(code) && !code.equals(userRegisterVO.getCode())) {
                    map.put("code", "验证错误");
                    model.addAttribute("error", map);
                    return "/register.html";
                }else {
                    redisTemplate.delete(key);
                    return "redirect:http://auth.mg.com/login.html";
                }

            }
        }

    }

//    @RequestMapping({"/register.html"})
//    public String register() {
//
//        return "/register";
//    }

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ResponseBody
    @RequestMapping({"/sms/send-sms"})
    public R sendSms(@RequestParam("phone") String phone) {
        String key = "mall-sms:" + phone;
        Object redisCode = redisTemplate.opsForValue().get(key);
        if (null != redisCode) {
            String redisCodeStr = redisCode.toString();

            Long time = Long.valueOf(redisCodeStr.split("-")[1]);
            Long nowTime = System.currentTimeMillis();

            if (nowTime - time < 6000) {
                return R.error("验证码已发");
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5);
//        thirdPartyFeignService.sendSmsCode(phone, code);

        String value = code + "-" + System.currentTimeMillis();

        redisTemplate.opsForValue().set(key, value, 100, TimeUnit.SECONDS);
        return R.ok();
    }
}
